<!-- 物品领用申请 -->
<template>
	<view class="page">
		<u--form labelPosition="top" :model="model" ref="form" :rules="rules" labelWidth="auto" :labelStyle="{
				fontSize: '14px',
				color: '#B2B2B2',
				lineHight: '20px'
			}">
			<view class="basic-style">
				<view class="basic-title basic-border">基本信息</view>
				<u-form-item label="单据编号" prop="purchaseBill" :borderBottom="false" required>
					<u--input disabled placeholder="请输入单据编号" v-model="model.purchaseBill"></u--input>
				</u-form-item>
				<u-form-item label="申请人" prop="handlerId" :borderBottom="false" required>
					<h-select-person-input style="width: 100%" disabled v-model="model.proposer" placeholder="请选择申请人"
						border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{color: '#B2B2B2'}"
						objectField="model.handlerId"></h-select-person-input>
				</u-form-item>
				<u-form-item label="申请部门" prop="departId" :borderBottom="false" required>
					<h-select-depart-input disabled v-model="model.departId" :departName="model.proposerDeptText"
						placeholder="请选择部门" border="surround" style="width: 100%" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						:title.sync="model.proposerDeptText"></h-select-depart-input>
				</u-form-item>
				<u-form-item label="申请日期" prop="createTime" :borderBottom="false" required>
					<u--input v-model="model.createTime" disabled placeholder="请选择申请日期" border="surround"
						suffixIcon="calendar-fill" :suffixIconStyle="{color: '#B2B2B2'}"></u--input>
				</u-form-item>
				<u-form-item label="领用团队" prop="teamId" required>
					<h-select-team-input style="width: 100%" v-model="model.teamId" objectField="model.teamId"
						placeholder="请选择领用团队" border="surround" :tdlx="3" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"></h-select-team-input>
				</u-form-item>
				<u-form-item label="备注" prop="remark" :borderBottom="false" ref="item1">
					<u--textarea v-model="model.remark" :confirmType="null" count placeholder="请输入备注"
						:maxlength="500"></u--textarea>
				</u-form-item>
			</view>
			<view class="basic-style">
				<view class="basic-title basic-border pt-1">物品领用明细</view>
				<view class="space-y-1 py-1">
				  <u-button size="small" type="primary" @click="addForm">新增</u-button>
				</view>
				<u-collapse>
				  <u-collapse-item :title="item.materialName_dictText" v-for="(item, index) in formData" :key="index">
				    <FormInfo :item="item" :index="index" @edit="handleEditForm" @remove="handleRemoveForm" @copy="handleCopyForm" />
				  </u-collapse-item>
				</u-collapse>
				<view @touchmove.stop.prevent="stopScroll">
					<u-popup mode="bottom" :show="showFormModal" @close="closeFormModal" @open="openFormModal">
					  <purchaseRecipientsForm ref="dataForm" :index="index" @submit="handleFormSubmit" @close="showFormModal = false" />
					</u-popup>
				</view>
				<!-- <view class="basic-title-center">
					<u-line :length="105"></u-line>
					<view class="">物品领用明细</view>
					<u-line :length="105"></u-line>
				</view>
				<ThingPurchaseRecipientsInfo ref="thingPurchaseRecipientsInfoRef" :dataList="model.detailList">
				</ThingPurchaseRecipientsInfo> -->
			</view>
			<view class="basic-style">
				<view class="basic-title basic-border">附件信息</view>
				<view class="py-1 space-y-1" style="width: 100%">
					<view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
					<h-upload-file v-model="model.purchaseFile" :isIcon="false" />
					<file-list v-if="model.purchaseFile" v-model="model.purchaseFile" :isDelete="true"></file-list>
				</view>
			</view>
			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
		</u--form>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
	</view>
</template>

<script>
	import fileList from '@/pages/synergy/components/fileList.vue'
	import moment from 'moment'
	import ThingPurchaseRecipientsInfo from './components/thingPurchaseRecipientsInfo.vue'
	import FormInfo from './components/purchaseRecipientsFormInfo.vue'
	import purchaseRecipientsForm from './components/purchaseRecipientsForm.vue'
	import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
	import {
		generatedFormNumber, // 获取单据编号
		erpPurchaseRecipientsAdd, //添加笔记本采购申请-保存
		erpPurchaseRecipientsEdit,
		queryByIdPurchaseRecipientsAllList, // 查看物品领用单信息物品领用明细
		queryByIdPurchaseRecipients, // 查看物品领用单信息
	} from '@/api/index.js'
	export default {
		components: {
			fileList,
			ThingPurchaseRecipientsInfo,
			FormInfo,
			purchaseRecipientsForm,
			ProcessNodeConfiguration
		},
		data() {
			return {
				id: '',
				model: {
					purchaseBill: '', // 单据编号
					proposer: '', // 申请人id
					departId: '', // 申请部门id
					proposerDeptText: '', //申请部门
					createTime: '', // 申请时间
					teamId: '', //所属团队
					remark: '', //备注
					detailList: [], //领用明细
					purchaseFile: null, //附件信息
				},
				rules: {
					teamId: [{
						required: true,
						message: '请选择领用团队!',
						trigger: 'change'
					}],
					purchaseBill: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
					departId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
					proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
					createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				},
				loading: false,
				isSubmit: false,
				flowCode: 'onl_erp_purchase_recipients',
				formUrl: '/erp/purchase/recipients/modules/ErpPurchaseRecipientsForm',
				formUrlMobile: '/pages/synergy/erpPurchaseRecipientsList',
				beanName: 'erpPurchaseRecipientsServiceImpl',
				processId: '1540222590478475266',
				index: null,
				showFormModal: false,
				formData:[],
				basicForm: {},
			}
		},
		onLoad(options) {
			if (options.id) {
				this.id = options.id
				this.edit(options.id)
			} else {
				// 添加
				this.add()
			}
		},
		methods: {
			stopScroll () {
				return false
			},
			addForm(){
				this.index = null
				this.showFormModal = true
			},
			handleEditForm([item, index]) {
			  this.basicForm = { ...item }
			  this.index = index
			  this.showFormModal = true
			},
			handleRemoveForm(item) {
			  this.formData = this.formData.filter((i) => i !== item)
			},
			closeFormModal() {
			  this.$refs.dataForm.reset()
			  this.basicForm = {}
			  this.index = null
				this.showFormModal = false
			},
			openFormModal() {
			  this.$refs.dataForm.basicForm = Object.assign({},this.basicForm)
			},
			/**
			 * 子表单新增点击确认
			 */
			handleFormSubmit(data, materialDetail) {
			  this.showFormModal = false
			  materialDetail.map(value => {
			  	this.formData.push({
						provisionBroad: value.provisionBroad,
						provisionBroad_dictText: value.provisionBroad_dictText,
			  		provisionSmall: value.provisionSmall, // 采购小类
			  		provisionSmall_dictText: value.provisionSmall_dictText, // 采购小类
			  		materialBill: value.materialBill, // 物料编码
			  		materialName: value.id, // 物料名称
			  		materialName_dictText: value.materialName, // 物料名称
			  		brand: value.brand, // 品牌
			  		specification: value.specification, // 规格型号
			  		referencePrice: value.referencePrice, // 参考价格
			  		unit: value.unit, // 单位
			  		unit_dictText: value.unit_dictText, // 单位
			  		amount: '', // 领用数量
			  		budgetAmount: '' // 预算价格
			  	})
			  })
			},
			// 添加
			add() {
				this.getGeneratedFormNumber()
				this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 申请时间
				this.model.proposer = uni.getStorageSync('userInfo').empId; //申请人id
				this.model.departId = uni.getStorageSync('userInfo').deptId; //申请部门id
			},
			async edit(id){
				const response = await queryByIdPurchaseRecipients({ id })
				const data = response?.result || {}
				this.model = await Object.assign({}, data)
				const res = await queryByIdPurchaseRecipientsAllList({ billId: id })
				this.formData = res.success?res.result : []
			},
			// 获取单据编号
			getGeneratedFormNumber() {
				generatedFormNumber({
					prefix: 'WPLY',
					subSystemCode: '04'
				}).then(res => {
					if (res.success) {
						this.$set(this.model, 'purchaseBill', res.result)
						this.$set(this.model, 'bpmBizTitle', uni.getStorageSync('userInfo')?.employee?.name + '-' + res.result)
					}
				})
			},
			// 获取流程列表
			getProcessList (id) {
				if (this.isSubmit) {
					this.$refs.processConfig.showPopup = true
					this.$refs.processConfig.formUrl = this.formUrl
					this.$refs.processConfig.formUrlMobile = this.formUrlMobile
					this.$refs.processConfig.flowCode = this.flowCode
					this.$refs.processConfig.edit(id, this.processId, this.beanName)
				}
			},
			// 提交流程成功
			onOk () {
				this.$refs.uToast.show({
					message: '提交成功',
					type: 'success',
					complete () {
						if (getCurrentPages().length > 1) {
							uni.navigateBack()
						} else {
							uni.reLaunch({
								url: '/pages/home/home'
							})
						}
						
					}
				})
			},
			validateForm() {
			  return this.$refs.form.validate().then(async () => {
			  if (!this.formData.length) {
			    this.$u.toast('请添加物品领用明细信息！')
			    return Promise.reject('请添加物品领用明细信息！')
			  }
			  // 判断数据有没有填写领用数量
			    var isAmount = this.formData.some(item => !item.recipientsNum);
			    if (isAmount) {
			      // 当为true说明有值领用数量没有填写
			      this.$u.toast('请填写物料明细中的领用数量！');
			      return Promise.reject('请填写物料明细中的领用数量！')
			    }
			    return Promise.resolve()
			  })
			},
			// 保存提交
			async onSubmit() {
				await this.validateForm()
				this.isSubmit = true
				try {
				  this.loading = true
					var url = ''
					if (this.id) {
						url = erpPurchaseRecipientsEdit
					} else {
						url = erpPurchaseRecipientsAdd
					}
				  const response = await url({
						...this.model,
						detailList: this.formData
					})
				  this.$u.toast(response.message)
				  if (response.success) {
				    var that = this
				    
				    // 获取流程列表
				    if (this.model.id) {
				    	this.getProcessList(this.model.id)
				    } else {
				    // 判断添加的时候是否有返回id值
				    	if (response.result) {
				    		this.getProcessList(response.result)
				    	}
				    
				    }
				    this.$refs.uToast.show({
				    	message: response.message,
				    	type: 'default',
				    	complete () {
				    		// that.isSubmit = false
				    	}
				    })
				  }
				} finally {
				  this.loading = false
				}
			},
			// 保存
			async onDraft() {
				// await this.validateForm()
				this.isSubmit = true
				try {
				  this.loading = true
					var url = ''
					if (this.id) {
						url = erpPurchaseRecipientsEdit
					} else {
						url = erpPurchaseRecipientsAdd
					}
				  const response = await url({
						...this.model,
						detailList: this.formData
					})
				  if (response.success) {
						this.$refs.uToast.show({
							message: response.message,
							type: 'default',
							complete () {
								this.isSubmit = false
								if (getCurrentPages().length > 1) {
									uni.navigateBack()
								} else {
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
								
							}
						})
				  } else {
						this.$refs.uToast.show({
							message: response.message,
			  			type: 'error'
						})
					}
				} finally {
				  this.loading = false
				}
			}
		}
	}
</script>


<style lang="scss" scoped>
	@import url("@/assets/inputStyle.scss");
</style>